/**
 * 
 */
package cn.com.elite;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ebao.gs.integration.sms.entity.SMSEntity;
import com.ebao.gs.integration.sms.module.SMS;
import com.ebao.gs.integration.sms.service.InternalSMSService;
import com.ebao.gs.integration.sms.sybase365.SMSSenderImpl;

/**
 * @author ralph.jiang
 * 
 */
@SuppressWarnings("serial")
public class TestServlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger(TestServlet.class);

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String no=req.getParameter("no");
		System.out.println(no);
		logger.info(no);
//		String content=req.getParameter("content");
//		content=URLDecoder.decode(content,"UTF-8");
//		System.out.println(content);
//		logger.info(content);
		InternalSMSService service = (InternalSMSService) WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()).getBean("com.ebao.gs.integration.sms.spi.SMSService");
		SMSSenderImpl senderImpl= (SMSSenderImpl) WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()).getBean("com.ebao.gs.integration.sms.spi.SMSSender");
		
		SMS sms = new SMS();
		sms.setSubject("AAAA");
		sms.setCritical(true);// will be resend ,otherwise will not.
		sms.setEstimatedSendTime(new Date());
		sms.setReceivers(Arrays.asList(new String[] {no}));
		sms.setText("测试测试");
		// first create sms entity
		Long[] smsIdArray = service.sendSMS(sms);
		resp.setContentType("text/html; charset=UTF-8");
		PrintWriter out = resp.getWriter();
		for (int i = 0; i < smsIdArray.length; i++) {
			String s = "SMS created id=" + smsIdArray[i];
			logger.info(s);
			out.print(s);
			out.println("<br/>");
		}
		out.close();
		
		
        while(true){
        	Collection<SMSEntity> smslist=service.findUnsendSMS(50);
        	if(smslist==null||smslist.isEmpty()){
        		break;
        	}
        	for(SMSEntity entity:smslist){
        		try{
        			List list=senderImpl.sendSMS(entity.toSMS());
        			logger.error("list:"+list);
        		}catch(Exception e){
        			logger.error(e.toString());
        		}
        	}
        }
	}
}